package com.hcc.flow.server.controller.flowDesign;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hcc.flow.server.annotation.LogAnnotation;
import com.hcc.flow.server.annotation.Original;
import com.hcc.flow.server.common.constant.Constant;
import com.hcc.flow.server.common.enums.CheckStatusType;
import com.hcc.flow.server.common.enums.DataStatusType;
import com.hcc.flow.server.common.enums.MsgType;
import com.hcc.flow.server.common.model.ApiResult;
import com.hcc.flow.server.common.page.table.PageTableHandler;
import com.hcc.flow.server.common.page.table.PageTableRequest;
import com.hcc.flow.server.common.page.table.PageTableResponse;
import com.hcc.flow.server.common.utils.CommUtil;
import com.hcc.flow.server.common.utils.StringUtilsV2;
import com.hcc.flow.server.common.vo.SelectValueVO;
import com.hcc.flow.server.common.where.PublicWhere;
import com.hcc.flow.server.dao.flowDesign.FlowDesignDao;
import com.hcc.flow.server.dao.flowDesign.FlowDesignTempDao;
import com.hcc.flow.server.dao.flowDesign.FlowTaskTypeDao;
import com.hcc.flow.server.dao.workbench.MsgNoticeDao;
import com.hcc.flow.server.dao.workbench.MsgNoticeReadDao;
import com.hcc.flow.server.dto.flowDesign.FlowDesignBaseDto;
import com.hcc.flow.server.dto.flowDesign.FlowDesignJsonDto;
import com.hcc.flow.server.model.flowDesign.FlowDesign;
import com.hcc.flow.server.model.flowDesign.FlowDesignTemp;
import com.hcc.flow.server.model.flowDesign.FlowTaskType;
import com.hcc.flow.server.model.workbench.MsgNotice;
import com.hcc.flow.server.model.workbench.MsgNoticeRead;
import com.hcc.flow.server.service.flowDesign.FlowService;
import com.hcc.flow.server.service.sys.UserService;
import com.hcc.flow.server.utils.UserUtil;
import com.hcc.flow.server.vo.flowDesign.FlowDesignJsonVO;
import com.hcc.flow.server.vo.flowDesign.FlowDesignVO;
import com.hcc.flow.server.vo.workbench.MsgNoticeReadVO;

import io.swagger.annotations.ApiOperation;
import net.sf.json.util.JSONUtils;

/**
 * 流程管理
 * @author admin
 *
 */
@RestController
@RequestMapping("/flows")
public class FlowDesignController {

    @Autowired
    private FlowDesignDao flowDao;
    @Autowired
	private FlowDesignTempDao flowTempDao;
    @Autowired
    private FlowService flowService;
    @Autowired
    private UserService userService;
    @Autowired
	private MsgNoticeDao msgNoticeDao;
	@Autowired
	private MsgNoticeReadDao msgNoticeReadDao;
	@Autowired
	private FlowTaskTypeDao flowTaskTypeDao;
	
	@LogAnnotation
    @PostMapping
    @ApiOperation(value = "流程基础-保存")
    @PreAuthorize("hasAuthority('sys:flow:add')")
    public ApiResult<?> save(@RequestBody FlowDesignBaseDto flowBaseDto) {
    	if(flowBaseDto == null){
    		return ApiResult.error("保存数据不能为空");
    	}
    	FlowDesign flow = new FlowDesign();
    	flow.setFlowId(flowBaseDto.getFlowId());
    	flow.setFlowCode(flowBaseDto.getFlowCode());
    	flow.setFlowName(flowBaseDto.getFlowName());
    	flow.setFlowType(flowBaseDto.getFlowType());
    	flow.setFlowRemarks(flowBaseDto.getFlowRemarks());
    	flow.setFollowOrgId(flowBaseDto.getFollowOrgId());
    	flow.setFlowAttribute(flowBaseDto.getFlowAttribute());
    	return flowService.save(flow);
    }
	@LogAnnotation
    @PutMapping
    @ApiOperation(value = "流程设计-走流程图-保存")
    @PreAuthorize("hasAuthority('sys:flow:design')")
    public ApiResult<?> save(@RequestBody FlowDesignJsonDto flowJsonDto) {
    	if(flowJsonDto == null){
    		return ApiResult.error("设计数据不能为空");
    	}
    	if(StringUtilsV2.isBlank(flowJsonDto.getFlowId())) {
    		return ApiResult.error("流程id不能为空");
    	}
    	FlowDesign flow = new FlowDesign();
    	flow.setFlowId(flowJsonDto.getFlowId());
    	flow.setFlowCode(flowJsonDto.getFlowCode());
    	flow.setFlowRemarks(flowJsonDto.getFlowRemarks());
    	flow.setFlowName(flowJsonDto.getFlowName());
    	String flowData = flowJsonDto.getFlowData();
    	if(StringUtilsV2.isNotBlank(flowData)) {
    		if(JSONUtils.mayBeJSON(flowData)) {
    			flow.setFlowData(flowData);
    		}else {
    			return ApiResult.error("流程设计内容不是JSON格式");
    		}
    	}
    	return flowService.edit(flow);
    }
    @GetMapping("/{id}")
    @ApiOperation(value = "流程-根据id获取")
    @PreAuthorize("hasAuthority('sys:flow:query')")
    public ApiResult<?> get(@PathVariable String id) {
        if(StringUtilsV2.isBlank(id)){
			return ApiResult.error("要查询的id不能为空");
		}
    	return ApiResult.data(flowDao.getById(id));
    }
    @GetMapping("/bese/{id}")
    @ApiOperation(value = "流程-根据id获取基础信息")
    @PreAuthorize("hasAuthority('sys:flow:query')")
    public ApiResult<?> baseget(@PathVariable String id) {
        if(StringUtilsV2.isBlank(id)){
			return ApiResult.error("要查询的id不能为空");
		}
    	return ApiResult.data(flowDao.getBaseById(id));
    }
    
    @GetMapping("/map2/{flowId}/{status}")
    @ApiOperation(value = "流程-根据id获取设计图信息")
    @PreAuthorize("hasAuthority('sys:flow:query') or hasAuthority('sys:msgNoticeRead:query')")
    public ApiResult<?> mapget2(@PathVariable String flowId,@PathVariable String status) {
        if(StringUtilsV2.isBlank(flowId)){
			return ApiResult.error("要查询的id不能为空");
		}
        FlowDesignJsonVO fjv = null;
        //status = 2 查看某个业务审批流程图模式
        if(!"2".equals(status)) {
        	fjv = flowDao.getJsonById(flowId);
        }else {
        	String readId = flowId;
        	MsgNoticeRead read = msgNoticeReadDao.getById(readId);
        	if(read == null) {
        		return ApiResult.error("该任务不存在");
        	}
        	MsgNotice msgNotice = msgNoticeDao.getById(read.getNoticeId());
        	if(msgNotice == null) {
        		return ApiResult.error("该任务不存在");
        	}
        	boolean resultMsg = false;
        	if(MsgType.RESULT.getCode().equals(msgNotice.getType()) && StringUtilsV2.isBlank(msgNotice.getFlowTempId())) {
        		msgNotice = msgNoticeDao.getMaxNewByFlowFromId(msgNotice.getFlowFromId(),msgNotice.getFlowSubmitNo(),msgNotice.getFlowTempId(),msgNotice.getFlowTempNodeId());
        		if(msgNotice == null) {
        			fjv = new FlowDesignJsonVO();
                	fjv.setFlowName("未找到该任务审核流程数据");
        			return ApiResult.data(fjv);
        			//return ApiResult.error("该结果消息对应任务不存在");
        		}
        		resultMsg = true;
        	}
        	fjv = flowDao.getTempJsonByTempId(msgNotice.getFlowTempId());
        	if(fjv == null) {
        		return ApiResult.error("该任务对应流程模板不存在");
        	}
        	JSONObject flow = null;
    		if(StringUtilsV2.isNotBlank(fjv.getFlowData())) {
    			if(JSONUtils.mayBeJSON(fjv.getFlowData())) {
    				flow = JSONObject.parseObject(fjv.getFlowData());
    			}else {
    				return ApiResult.error("流程副本("+fjv.getFlowName()+")设计内容格式不是JSON格式");
    			}
    		}
    		if(flow == null) {
    			return ApiResult.error("流程副本("+fjv.getFlowName()+")设计不能为空");
    		}
    		MsgNotice newMsgNotice;
    		if(!resultMsg)
    			newMsgNotice = msgNoticeDao.getMaxNewByFlowFromId(msgNotice.getFlowFromId(),msgNotice.getFlowSubmitNo(),msgNotice.getFlowTempId(),null);
    		else {
    			newMsgNotice = msgNotice;
    		}
			if(newMsgNotice == null) {
				return ApiResult.error("流程任务最新节点任务为空");
			}
			ApiResult<JSONObject> beginAr = flowService.getNodeBeginOrEnd(flow, null, 0);
			if(!beginAr.isSuccess()) {
				return beginAr;
			}
			ApiResult<JSONObject> endAr = flowService.getNodeBeginOrEnd(flow, null, 1);
			if(!endAr.isSuccess()) {
				return endAr;
			}
			boolean y = false;
			if(endAr.getData().getInteger("top")-beginAr.getData().getInteger("top") > 100) {
				y = true;
			}
    		JSONObject nodes = flow.getJSONObject("nodes");
    		//JSONObject nodesMsg = new JSONObject();
    		Map<String, Object> nodesMsgMap = new HashMap<>();
    		JSONObject lines = flow.getJSONObject("lines");
        	JSONObject node;
        	JSONObject nodeMsg;
        	JSONObject line;
        	List<MsgNoticeReadVO> nodeVerifyVo = new ArrayList<MsgNoticeReadVO>();
        	//所有审批记录（时间倒叙）
        	List<MsgNoticeReadVO> nodeVerifyVoAll = msgNoticeDao.getNoticeReadVOByMore(msgNotice.getFlowFromId(),msgNotice.getFlowSubmitNo(),msgNotice.getFlowTempId(),null,true,0);
    		ApiResult<JSONObject> beginNodeAr = flowService.getNodeBeginOrEnd(flow, null, 0);
    		if(!beginNodeAr.isSuccess()) {
    			return beginNodeAr;
    		}
    		String beginNodeId = beginNodeAr.getMsg();
    		//有序的任务节点集合key
    		List<String> sortKeys = new ArrayList<String>();
    		sortKeys.add(beginNodeId);
    		Set<String> linekeys = lines.keySet();
    		sortKey(lines,linekeys,sortKeys,beginNodeId);
    		boolean endCom = false;//已到达终点节点
			for (String key : sortKeys) {
				nodeVerifyVo = new ArrayList<MsgNoticeReadVO>();
				node = nodes.getJSONObject(key);
				int verifyJoint = node.getIntValue("verifyJoint");//节点规则
				int verifyType = node.getIntValue("verifyType");//节点审核类型
				String verifyTypeStr = "";
				if(verifyType == 3) {
					verifyTypeStr = "用户";
				}else if(verifyType == 2) {
					verifyTypeStr = "角色";
				}else {
					verifyTypeStr = "机构";
				}
				int i = 0;
				if("start round mix".equals(node.getString("type"))) {
					if(!nodeVerifyVoAll.isEmpty()) {
						nodeVerifyVo.add(nodeVerifyVoAll.get(0));
					}
					i = 1;
				}else if("end round mix".equals(node.getString("type"))) {
					if(!nodeVerifyVoAll.isEmpty()) {
						nodeVerifyVo.add(nodeVerifyVoAll.get(nodeVerifyVoAll.size()-1));
					}
					i = 2;
				}else if("task".equals(node.getString("type"))){
					int torderBy = 0;
					if(verifyJoint != 0) {
						torderBy = 1;
					}
					nodeVerifyVo = msgNoticeDao.getNoticeReadVOByMore(msgNotice.getFlowFromId(),msgNotice.getFlowSubmitNo(),msgNotice.getFlowTempId(),key,(verifyJoint == 0),torderBy);
					i = 3;
				}
				if(!nodeVerifyVo.isEmpty()) {
					nodeMsg = new JSONObject();
					if(y) {
						if(i == 3) {
							nodeMsg.put("width", 300);
							nodeMsg.put("left", node.getInteger("left")+200);
							nodeMsg.put("top", node.getInteger("top")-20);
						}else {
							nodeMsg.put("width", 240);
							nodeMsg.put("left", node.getInteger("left")+160);
							nodeMsg.put("top", node.getInteger("top"));
						}
					}else {
						nodeMsg.put("left", node.getInteger("left")-20);
						nodeMsg.put("top", node.getInteger("top")+200);
						if(i == 3) {
							nodeMsg.put("width", node.getInteger("width")+70);
						}else {
							nodeMsg.put("width", 240);
						}
					}
					
					nodeMsg.put("alt", true);
					nodeMsg.put("type", "chat");
					
					line = new JSONObject();
					line.put("tyle", "sl");
					line.put("name", "");
					line.put("to", key+"-msg");
					line.put("from", key);
					line.put("marked", true);
					lines.put(key+"-line", line);
					
					int adopt = 0;//通过个数
					int retu = 0;//驳回个数
					int doof = 0;//转办个数
					int wait = 0;//审核中个数
					StringBuffer son = new StringBuffer();
					List<String> auditedUserNames = new ArrayList<>();//当前节点的未处理消息的用户
					List<String> waitAuditedUserNames = new ArrayList<>();//当前节点的未处理消息的用户
					SelectValueVO lastAudited = new SelectValueVO();
					SelectValueVO lastRefused = new SelectValueVO();
					for (MsgNoticeReadVO rv : nodeVerifyVo) {
						if(!CheckStatusType.WAIT_AUDITED.getCode().equals(rv.getFlowVerifyStatus())) {
							if(i == 3) {
								if(StringUtilsV2.isNotBlank(rv.getFlowVerifyStatusName())) {
									son.append("审核状态: ").append(rv.getFlowVerifyStatusName()).append("<br/>");
									String flowVerifyReason = rv.getFlowVerifyReason();
									if(!flowVerifyReason.startsWith("该任务已被他人")) {
										son.append("审核人员: ").append(rv.getReadUserName()).append("<br/>");
									}
									son.append("审核时间: ").append(CommUtil.formatLongDate(rv.getReadTime())).append("<br/>");
									son.append("审核说明: ").append(flowVerifyReason);
								}else {
									son.append("审核状态: ").append(CheckStatusType.WAIT_AUDITED.getName()).append("<br/>");
									son.append("审核说明: ").append("等待节点相关审核者-").append(verifyTypeStr)
														.append("(").append(node.getString("verifyModelNames")).append(")审核中");
									wait++;
								}
							}else if(i == 1) {
								son.append("提交人员: ").append(rv.getPushUserName()).append("<br/>");
								son.append("提交时间: ").append(CommUtil.formatLongDate(rv.getPushTime()));
							}else if(i == 2) {
								son.append("结束人员: ").append(rv.getReadUserName()).append("<br/>");
								son.append("结束时间: ").append(CommUtil.formatLongDate(rv.getReadTime()));
							}
							if(CheckStatusType.AUDITED.getCode().equals(rv.getFlowVerifyStatus())) {
								adopt++;
								if(verifyJoint == 0) {
									auditedUserNames.add(rv.getReadUserName());
								}else {
									auditedUserNames.add(rv.getReadUserName()+" "+CommUtil.formatTime("MM-dd HH:mm",rv.getReadTime()));
								}
								lastAudited.setId(rv.getReadUserName());
								lastAudited.setName(CommUtil.formatLongDate(rv.getReadTime()));
								lastAudited.setValue(rv.getFlowVerifyReason());
							}
							if(CheckStatusType.REFUSED.getCode().equals(rv.getFlowVerifyStatus()) && rv.getReadTime() != null) {
								retu++;
								lastRefused.setId(rv.getReadUserName());
								lastRefused.setName(CommUtil.formatLongDate(rv.getReadTime()));
								lastRefused.setValue(rv.getFlowVerifyReason());
							}
							if(CheckStatusType.DOOFFICE.getCode().equals(rv.getFlowVerifyStatus())) {
								doof++;
							}
						}else {
							wait++;
							waitAuditedUserNames.add(rv.getReadUserName());
						}
					}
					if(i == 3) {
						//审核通过
						if((adopt+doof) == nodeVerifyVo.size()) {
							nodeMsg.put("color", "green");
							nodeMsg.put("bg_color", "#DAEFB4");
							if(!endCom) {
								ApiResult<Boolean> downNodeIsEndAr = flowService.nodeNextNodeIsEnd(flow, null, key);
		    					if(!downNodeIsEndAr.isSuccess()) {
		    						return downNodeIsEndAr;
		    					}
								if(downNodeIsEndAr.getData()) {
									ApiResult<?> nextNodeIdAr = flowService.upOrDownNodeId(flow, null, key, 1);
									if(!nextNodeIdAr.isSuccess()) {
			    						return nextNodeIdAr;
			    					}
		    						String endNodeId = nextNodeIdAr.getData().toString();
		    						ApiResult<JSONObject> endNodeAr = flowService.getNode(flow, null, endNodeId);
		    						if(!endNodeAr.isSuccess()) {
		        						return endNodeAr;
		        					}
		    						JSONObject endNode = endNodeAr.getData();
		    						endNode.put("markedNew", true);
		    						nodes.put(endNodeId, endNode);
		    						endCom = true;
		    						
		    					}
							}
							if(verifyJoint == 1) {
								son = new StringBuffer();
								son.append("处理状态:会签节点相关人员全部核准").append("<br/>");
								String lastReamkVal = lastAudited.getValue() != null?lastAudited.getValue():"";
								if(!lastReamkVal.startsWith("该任务已被他人")) {
									son.append("所有审核者: ").append(verifyTypeStr).append("-[").append(node.getString("verifyModelNames")).append("]").append("<br/>");
									son.append("最后审核人: ").append(lastAudited.getId()).append("<br/>");
								}
								son.append("最后审核时间: ").append(lastAudited.getName()).append("<br/>");
								son.append("最后审核说明: ").append(lastReamkVal);
							}
							nodeMsg.put("name", son.toString());
							nodesMsgMap.put(key+"-msg", nodeMsg);
						}else if(wait == (nodeVerifyVo.size()-doof)) {//全部未审核
							son = new StringBuffer();
							son.append("处理状态: ").append(CheckStatusType.WAIT_AUDITED.getName()).append("<br/>");
							son.append("任务归属: ").append(verifyTypeStr).append("-[").append(node.getString("verifyModelNames")).append("]");
							nodeMsg.put("color", "#FF8800");
							nodeMsg.put("bg_color", "#FFF2D1");
						}else if(retu > 0) {//有驳回
							if(verifyJoint == 1) {
								son = new StringBuffer();
								son.append("处理状态:会签节点有归属者做了驳回处理").append("<br/>");
								if(auditedUserNames.size() > 0) {
									son.append("通过人员: ");
									if(auditedUserNames.size() > 5) {
										son.append(String.join(",", auditedUserNames.subList(0, 5))).append("...").append("<br/>");
									}else {
										son.append(String.join(",", auditedUserNames)).append("<br/>");
									}
								}
								String lastReamkVal = lastAudited.getValue() != null?lastAudited.getValue():"";
								if(!lastReamkVal.startsWith("该任务已被他人")) {
									son.append("驳回人员: ").append(lastRefused.getId()).append("<br/>");
								}
								son.append("驳回时间: ").append(lastRefused.getName()).append("<br/>");
								son.append("驳回说明: ").append(lastReamkVal);
							}
							nodeMsg.put("color", "red");
							nodeMsg.put("bg_color", "#FFD7D1");
							if(!endCom) {
								ApiResult<Boolean> downNodeIsEndAr = flowService.nodeNextNodeIsEnd(flow, null, key);
		    					if(!downNodeIsEndAr.isSuccess()) {
		    						return downNodeIsEndAr;
		    					}
								if(downNodeIsEndAr.getData()) {
									ApiResult<?> nextNodeIdAr = flowService.upOrDownNodeId(flow, null, key, 1);
									if(!nextNodeIdAr.isSuccess()) {
			    						return nextNodeIdAr;
			    					}
		    						String endNodeId = nextNodeIdAr.getData().toString();
		    						ApiResult<JSONObject> endNodeAr = flowService.getNode(flow, null, endNodeId);
		    						if(!endNodeAr.isSuccess()) {
		        						return endNodeAr;
		        					}
		    						JSONObject endNode = endNodeAr.getData();
		    						endNode.put("markedNew", true);
		    						nodes.put(endNodeId, endNode);
		    						endCom = true;
		    					}
							}
						}else if(doof == nodeVerifyVo.size()) {//全转办
							son.append("处理状态: ").append(CheckStatusType.DOOFFICE.getName());
							nodeMsg.put("color", "blue");
							nodeMsg.put("bg_color", "#CCE1F5");
						}else if(verifyJoint == 1 && (nodeVerifyVo.size()-doof) > adopt){//部分通过
							son = new StringBuffer();
							son.append("处理状态:会签节点部分人员已处理").append("<br/>");
							son.append("已处理人: ");
							if(auditedUserNames.size() > 5) {
								son.append(String.join(",", auditedUserNames.subList(0, 5))).append("...").append("<br/>");
							}else {
								son.append(String.join(",", auditedUserNames)).append("<br/>");
							}
							son.append("未处理人: ");
							if(auditedUserNames.size() > 5) {
								son.append(String.join(",", waitAuditedUserNames.subList(0, 5))).append("...").append("<br/>");
							}else {
								son.append(String.join(",", waitAuditedUserNames)).append("<br/>");
							}
							son.append("处理进度(已处理数/总数): "+(adopt+retu)+"/"+(adopt+retu+wait));
							nodeMsg.put("color", "#FF8800");
							nodeMsg.put("bg_color", "#FFF2D1");
						}
						if(key.equals(msgNotice.getFlowTempNodeId())) {
							node.put("marked", true);
							son.append("<br/><span style='color:#FF8800;'>").append("◆当前任务/消息所对应的任务节点").append("</span>");
						}
						nodeMsg.put("name", son.toString());
						nodesMsgMap.put(key+"-msg", nodeMsg);
					}else if(i == 1){
						nodeMsg.put("color", "green");
						nodeMsg.put("bg_color", "#DAEFB4");
						nodeMsg.put("name", son.toString());
						nodesMsgMap.put(key+"-msg", nodeMsg);
					}else if(i == 2 && endCom) {
						nodeMsg.put("color", "red");
						nodeMsg.put("bg_color", "#FFD7D1");
						//nodeMsg.put("name", "该流程已结束");
						son.setLength(0);
						son.append("该流程已结束");
						nodeMsg.put("name", son.toString());
						nodesMsgMap.put(key+"-msg", nodeMsg);
					}
				}
			}
			nodes.putAll(nodesMsgMap);
			if(!endCom) {
				//最新
				ApiResult<JSONObject> arNew = flowService.getNode(flow, null, newMsgNotice.getFlowTempNodeId());
				if(!arNew.isSuccess()) {
					return arNew;
				}
				JSONObject nodeNew = arNew.getData();
				nodeNew.put("markedNew", true);
				nodes.put(newMsgNotice.getFlowTempNodeId(), nodeNew);
			}
			fjv.setFlowData(flow.toJSONString());
        }
        if(fjv == null) {
        	fjv = new FlowDesignJsonVO();
        	fjv.setFlowName("未找到该流程数据");
        }
    	return ApiResult.data(fjv);
    }
    private void sortKey(JSONObject lines,Set<String> linekeys,List<String> sortKeys,String lineId) {
    	for (String key : linekeys) {
    		JSONObject line = lines.getJSONObject(key);
			if(lineId.equals(line.getString("from"))) {
				sortKeys.add(line.getString("to"));
				sortKey(lines,linekeys,sortKeys,line.getString("to"));
				break;
			}
		}
    }
    @GetMapping("/log/{id}")
    @ApiOperation(value = "流程-操作日志")
    @PreAuthorize("hasAuthority('sys:flow:query')")
    public ApiResult<?> log(@PathVariable String id) {
        if(StringUtilsV2.isBlank(id)){
			return ApiResult.error("要查询的id不能为空");
		}
    	return ApiResult.data(flowTempDao.getLogByFlowId(id));
    }
    @LogAnnotation
    @DeleteMapping("/{id}")
    @ApiOperation(value = "流程-逻辑删除")
    @PreAuthorize("hasAuthority('sys:flow:del')")
    public ApiResult<?> editStatusDelete(@PathVariable String id) {
    	if(StringUtilsV2.isBlank(id)){
    		return ApiResult.error("要停用的数据ID不能为空");
    	}
        return flowService.delete(id);
    }
    @LogAnnotation
    @DeleteMapping("/status/{id}")
    @ApiOperation(value = "流程-启用")
    @PreAuthorize("hasAuthority('sys:flow:stop')")
    public ApiResult<?> stop(@PathVariable String id) {
    	if(StringUtilsV2.isBlank(id)){
    		return ApiResult.error("要操作的数据ID不能为空");
    	}
    	FlowDesign flow =flowDao.getById(id);
    	if(flow != null) {
    		String userId = UserUtil.getLoginUser().getUserId();
    		String editStatus;
    		if(DataStatusType.NORMAL.getCode().equals(flow.getStatus())) {
    			editStatus = DataStatusType.STOP.getCode();
    			List<FlowDesign> list = flowDao.getByOrgIdAndStatusAndAttribute(flow.getFollowOrgId(),flow.getFlowType(), Constant.DATA_STATUS_TYPE_NORMAL, flow.getFlowAttribute());
    			if(list.size() == 1) {
    				String flowAttributeName = "未知流程";
    				if("0".equals(flow.getFlowAttribute())){
    					flowAttributeName = "普通流程";
    				}else if("1".equals(flow.getFlowAttribute())){
    					flowAttributeName = "复合流程";
    				}
    				FlowTaskType flowTaskType= flowTaskTypeDao.getById(flow.getFlowType());
    				if(flowTaskType == null){
    					return ApiResult.error("通过类型ID("+flow.getFlowType()+")未找到对应流程业务类型");
    				}
    				return ApiResult.error("流程停用失败，该机构目前只有一个"+flowTaskType.getTaskTypeName()
    				+flowAttributeName
    				+"流程时，不能停用");
    			}
    		}else{
    			editStatus = DataStatusType.NORMAL.getCode();
    			ApiResult<?> ar = flowService.flowCheck(null, flow.getFlowData());
    			if(!ar.isSuccess()) {
    				ar.setMsg(DataStatusType.getName(editStatus)+"失败,原因:"+ar.getMsg());
    				return ar;
    			}
    			List<FlowDesign> list = flowDao.getByOrgIdAndStatusAndAttribute(flow.getFollowOrgId(),flow.getFlowType(), Constant.DATA_STATUS_TYPE_NORMAL, flow.getFlowAttribute());
    			if(list.size() > 0) {
    				List<String> ids =  new ArrayList<>();
    				for (FlowDesign flow2 : list) {
    					FlowDesignTemp temp = new FlowDesignTemp();
    					temp.setFlowId(flow2.getFlowId());
    					temp.setFlowCode(flow2.getFlowCode());
    					temp.setFlowName(flow2.getFlowName());
    					temp.setFlowRemarks(flow2.getFlowRemarks());
    					temp.setFlowData(flow2.getFlowData());
    					temp.setEditLog(DataStatusType.STOP.getCode()+"流程:自动(该机构其他["+("0".equals(flow.getFlowAttribute())?"普通":"复合")+"]流程["+flow.getFlowName()+"]手动启用时将此流程自动改为停用状态)");
    					temp.setCreateUserId(userId);
    					flowTempDao.save(temp);
    					ids.add(flow2.getFlowId());
					}
    				flowDao.updateStatus(ids, DataStatusType.STOP.getCode());
    			}
    		}
			flowDao.updateStatus(Arrays.asList(id),editStatus);
	    	FlowDesignTemp temp = new FlowDesignTemp();
			temp.setFlowId(flow.getFlowId());
			temp.setFlowCode(flow.getFlowCode());
			temp.setFlowName(flow.getFlowName());
			temp.setFlowRemarks(flow.getFlowRemarks());
			temp.setFlowData(flow.getFlowData());
			temp.setEditLog(DataStatusType.getName(editStatus)+"流程:手动");
			temp.setCreateUserId(userId);
			flowTempDao.save(temp);
    		return ApiResult.ok();
    	}else {
    		return ApiResult.error("未找到流程");
    	}
    }
    
    @PostMapping("/list")
	@ApiOperation(value = "流程 - 列表（分页）- vue版本预留")
	@PreAuthorize("hasAuthority('sys:flow:query')")
	public PageInfo<FlowDesignVO> ListNew(@RequestBody PublicWhere strCon) {
    	if(StringUtilsV2.isBlank(strCon.getChildOrgIds())) {
    		userService.setOrgIdAndRoleIds(strCon,"sys:flow:query");
    	}
		PageHelper.startPage(strCon.getOffset(), strCon.getLimit());
		if (StringUtilsV2.isBlank(strCon.getSqlOrder())) {
			strCon.setSqlOrder("create_time desc ");
		}
		PageHelper.orderBy(strCon.getSqlOrder());
		List<FlowDesignVO> list = flowDao.FlowList(strCon);
		PageInfo<FlowDesignVO> result = new PageInfo<FlowDesignVO>(list);
		return result;
	}
	
    @GetMapping
	@ApiOperation(value = "流程 - 列表（分页）- html版本")
	@Original
	public PageTableResponse LogListNew(PageTableRequest  strCon) {
    	PublicWhere where = new PublicWhere(strCon);
    	if(StringUtilsV2.isBlank(where.getChildOrgIds())) {
    		userService.setOrgIdAndRoleIds(where,"sys:flow:query");
    	}
		PageHelper.startPage(where.getOffset(), where.getLimit());
		if (StringUtilsV2.isBlank(where.getSqlOrder())) {
			where.setSqlOrder("t.create_time desc");
		}
		PageHelper.orderBy(where.getSqlOrder());
		List<FlowDesignVO> list = flowDao.FlowList(where);
		PageInfo<FlowDesignVO> result = new PageInfo<FlowDesignVO>(list);
		return new PageTableHandler(new PageTableHandler.CountHandler() {
			@Override
			public int count(PageTableRequest request) {
				return CommUtil.null2Int(result.getTotal());
			}
		}, new PageTableHandler.ListHandler() {
			@Override
			public List<FlowDesignVO> list(PageTableRequest request) {
				return result.getList();
			}
		}).handle(strCon);
	}
}
